package com.anatolyrodin;

import java.util.NoSuchElementException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: SuperHuman
 * Date: 20.01.14
 * Time: 06:29 PM
 * To change this template use File | Settings | File Templates.
 */

public class IpManager {

    private String[] ipArray = {"192.168.0.4","192.168.0.1", "192.168.0.4", "192.168.0.1", "192.168.0.6",
                                "192.168.0.0", "192.168.0.8", "192.168.0.0", "192.168.0.2", "192.168.0.3"};

    private long[] ipIntArray;


    public static void main(String[] args) {

        new IpManager().go();

    }

    public void go() {

        long range, range2;
        String temp1, temp2;

        System.out.println("Диапазон адресов:");
        for(String print: ipArray) {
            System.out.print(print + ", ");
        }

        initialization();
            try {
                Scanner scanner = new Scanner(System.in);

                System.out.println("\nВведите начало диапазона: ");
                temp1 = scanner.next();
                System.out.println("Введите конец диапазона: ");
                temp2 = scanner.next();

                System.out.println();

                range = ipToLong(temp1);
                range2 = ipToLong(temp2);

                for(int i = 0; i < ipIntArray.length; i++) {

                    if(range < ipIntArray[i] && range2 > ipIntArray[i]) {

                        System.out.println(longToString(ipIntArray[i]));
                    }
                }
            } catch (NoSuchElementException ex) {
                ex.printStackTrace();
            } catch (NumberFormatException ex2) {
                System.out.println("Неверно указан(ы) ip-адрес(а)");
            }

    }

    public void initialization() {

        ipIntArray = new long[ipArray.length];

        for(int i = 0; i < ipArray.length; i++) {

            ipIntArray[i] = ipToLong(ipArray[i]);
        }

        // sort
        for(int i = 0; i < ipIntArray.length-1; i++) {

            for(int j = i + 1; j < ipIntArray.length; j++) {

                if(ipIntArray[i]>ipIntArray[j]){

                    long tmp = ipIntArray[i];
                    ipIntArray[i] = ipIntArray[j];
                    ipIntArray[j] = tmp;
                }
            }
        }
    }

    public long ipToLong(String address) {

        String[] addressArray = address.split("\\.");

        long result = 0;
        for(int i = 0; i < addressArray.length; i++) {

            int rate = 3 - i;
            int ip = Integer.parseInt(addressArray[i]);
            result += ip * Math.pow(256, rate);

        }
        return result;
    }

    public String longToString(long i) {

         return ((i >> 24) & 0xFF) +
                "." + ((i >> 16) & 0xFF) +
                "." + ((i >> 8) & 0xFF) +
                "." + (i & 0xFF);
    }
}
